// 树形结构化

let data = [
  {
    id: 1,
    pid: 0,
    title: 'aaa',
    path: '/a'
  },
  {
    id: 4,
    pid: 0,
    title: 'ddd',
    path: '/d'
  },
  {
    id: 2,
    pid: 1,
    title: 'bbb',
    path: '/a/b'
  },
  {
    id: 3,
    pid: 2,
    title: 'ccc',
    path: '/a/b/c'
  }
]

/*
function formatToTree(data) {
  let parents = data.filter(p => p.pid === 0),
      children = data.filter(c => c.pid !== 0)

  formatData(parents, children)

  function formatData(parents, children) {
    parents.map(p => {
      children.map((c, index) => {
        if (c.pid === p.id) {
          let _children = JSON.parse(JSON.stringify(children))
          _children.splice(index, 1)

          formatData([c], _children)
          if (p.children) {
            p.children.push(c)
          } else {
            p.children = [c]
          }
        }
      })
    })
  }

  return parents
}

console.log(formatToTree(data))*/

function formatToTree(data) {
  let result = [],
      map = new Map()
  data.forEach((item) => {
    map.set(item.id, item)
  })
  console.log('map:', map)
  data.forEach((item) => {
    let parent = map.get(item.pid)
    if (parent) {
      if (parent.children) {
        parent.children.push(item)
      } else {
        parent.children = [item]
      }
    } else {
      result.push(item) // 顶级节点
    }
  })
  return result
}

console.log(formatToTree(data))